/* 
 * File:   FilePart.cpp
 * Author: Fei Fan
 * E-mail: ffinuyasha@sina.com
 * Copyright © 2013 Fei Fan, All Rights Reserved
 */

#include"FileMng.h"

//将硬盘扇区号转为文件号

//char* SecterPath(char *filename, int num) {
//    strcpy(filename, "C:\\HD\\sect000");
//    int n;
//    n = num % 10;
//    filename[12] = '0' + n;
//    num = num / 10;
//    n = num % 10;
//    filename[11] = '0' + n;
//    num = num / 10;
//    filename[10] = '0' + num;
//
//    return filename;
//}

char* memoZonePath(char *filename, int num) {
    strcpy(filename, "..\\MEMO\\zone000");
    int n;
    n = num % 10;
    filename[14] = '0' + n;
    num = num / 10;
    n = num % 10;
    filename[13] = '0' + n;
    num = num / 10;
    filename[12] = '0' + num;

    return filename;

}

char* remoteSecterPath(char *filename, char *terName, int num) {
    char numChar[4];
    int n;
    strcpy(filename, "..\\");
    strcat(filename, terName);
    if (num != FIND_TERMINAL) {
        numChar[3] = '\0';
        n = num % 10;
        numChar[2] = '0' + n;
        num = num / 10;
        n = num % 10;
        numChar[1] = '0' + n;
        num = num / 10;
        numChar[0] = '0' + num;
        strcat(filename, "\\sect");
        strcat(filename, numChar);
    }
    return filename;
}

char* SecterPath(char *filename, int num) {
    strcpy(filename, "sect000");
    int n;
    n = num % 10;
    filename[6] = '0' + n;
    num = num / 10;
    n = num % 10;
    filename[5] = '0' + n;
    num = num / 10;
    filename[4] = '0' + num;

    return filename;
}

int isExist(char *terName, int num) {
    struct _finddata_t info;
    long res;
    char filename[50];

    if (strcmp(terName, "\0")) {
        res = _findfirst(remoteSecterPath(filename, terName, num), &info);
        if (res == -1)
            return FAIL;
    } else {
        res = _findfirst(SecterPath(filename, num), &info);
        if (res == -1)
            return FAIL;
    }
    return SUCCESS;
}


//初始化硬盘

void HDformat() {
    int i;
    FILE *fp;
    char filename[25];
    char strDir[50];
    //格式化硬盘上的文件
    for (i = 0; i < VOL_HD; i++) {
        remove(SecterPath(filename, i));
    }
    for (i = 0; i < VOL_HD; i++) {
        fp = fopen(SecterPath(filename, i), "w");
        fclose(fp);
    }

    long nowTime;
    nowTime = time(&nowTime);

    //将基本内容：基本目录文件、空闲块文件、用户文件等写入硬盘

    //sect000  基本目录文件
    fp = fopen(SecterPath(filename, SECT_BASE), "w");
    BaseSect baseSect;
    baseSect.HeadIndexSect = SECT_HEADINDEX;
    //	baseSect.userSect=SECT_USERDIR;
    baseSect.vacantSect = SECT_VACDIR;
    fwrite(&baseSect, sizeof (BaseSect), 1, fp);
    fclose(fp);


    //sect254  文件头的索引块
    fp = fopen(SecterPath(filename, SECT_HEADINDEX), "w");
    HeadIndex hIdx[INDEX_MAX];

    strcpy(hIdx[0].name, "/");
    hIdx[0].PMS = READ;
    hIdx[0].sects[0] = SECT_ROOTDIR;
    hIdx[0].type = TYPE_DIR;
    hIdx[0].size = 1;
    hIdx[0].modTime = nowTime;
    hIdx[0].rdCnt = 0;
    hIdx[0].wrtCnt = 0;

    strcpy(hIdx[1].name, "/sys");
    hIdx[1].PMS = NONE;
    hIdx[1].sects[0] = SECT_SYSDIR;
    hIdx[1].type = TYPE_DIR;
    hIdx[1].size = 1;
    hIdx[1].modTime = nowTime;
    hIdx[1].rdCnt = 0;
    hIdx[1].wrtCnt = 0;

    strcpy(hIdx[2].name, "/sys/psd");
    hIdx[2].PMS = NONE;
    hIdx[2].sects[0] = SECT_PSDFILE;
    hIdx[2].type = TYPE_FILE;
    hIdx[2].size = 1;
    hIdx[2].modTime = nowTime;
    hIdx[2].rdCnt = 0;
    hIdx[2].wrtCnt = 0;

    strcpy(hIdx[3].name, "/sys/vac");
    hIdx[3].PMS = NONE;
    hIdx[3].sects[0] = SECT_VACDIR;
    hIdx[3].type = TYPE_FILE;
    hIdx[3].size = 1;
    hIdx[3].modTime = nowTime;
    hIdx[3].rdCnt = 0;
    hIdx[3].wrtCnt = 0;

    //	strcpy(hIdx[4].name,"/online");
    //	hIdx[4].PMS=NONE;
    //	hIdx[4].sects[0]=SECT_ONLINE;
    //	hIdx[4].type=TYPE_FILE;
    //	hIdx[4].size=1;
    //	hIdx[4].modTime=nowTime;
    //	hIdx[4].rdCnt=0;
    //	hIdx[4].wrtCnt=0;

    //for(i=5;i<INDEX_MAX;i++){
    for (i = 4; i < INDEX_MAX; i++) {
        hIdx[i].type = TYPE_NONE;
    }


    fwrite(&hIdx, sizeof (HeadIndex), INDEX_MAX, fp);
    fclose(fp);

    //sect255  用户目录
    fp = fopen(SecterPath(filename, SECT_ROOTDIR), "w");
    //初始时，只有/sys
    strcpy(strDir, "-------");
    buildDir(strDir, "sys", "no", 'd', nowTime);
    fwrite(strDir, sizeof (char), 50, fp);
    fclose(fp);


    //sect256  VacantBLock目录
    fp = fopen(SecterPath(filename, SECT_VACDIR), "w");
    VacantTable VacantBlock;
    //初始时，只有两个空闲块
    VacantBlock.sectNum = 2;
    VacantBlock.start[0] = 1; //这里这一位作为起始块号
    VacantBlock.len[0] = SECT_HEADINDEX - 1; //这里这一位作为连续块数量
    VacantBlock.start[1] = SECT_PSDFILE + 1;
    VacantBlock.len[1] = VOL_HD - SECT_PSDFILE - 1;
    fwrite(&VacantBlock, sizeof (VacantTable), 1, fp);
    fclose(fp);
    //    fp = fopen(SecterPath(filename, SECT_VACDIR), "r");
    //    fread(&VacantBlock, sizeof (VacantTable), 1, fp);
    //    int tempN=VacantBlock.sectNum;
    //    printf("%d\n",tempN);
    //    for(int tempI=0;tempI<tempN;tempI++) printf("start:%hd      len:%hd\n",VacantBlock.start[tempI],VacantBlock.len[tempI]);
    //    fclose(fp);



    //sect257  sys目录
    fp = fopen(SecterPath(filename, SECT_SYSDIR), "w");
    //初始时，root用户下只有密码文件and vac
    strcpy(strDir, "-------");
    buildDir(strDir, "psd", "no", 'f', nowTime);
    buildDir(strDir, "vac", "no", 'f', nowTime);
    fwrite(strDir, sizeof (char), 100, fp);
    fclose(fp);

    //sect258 psd文件
    fp = fopen(SecterPath(filename, SECT_PSDFILE), "w");
    User rootUser[USER_MAX];
    //初始时，密码文件里只有root用户
    strcpy(rootUser[0].name, MyName);
    strcpy(rootUser[0].psd, MyPassword);
//    printf("format: %s\n",rootUser[0].name);
//        //----------------------------------------------------------------------------------------------------
//         for (int tempi = 0; tempi < 16; tempi++)
//                printf("%02X", (unsigned char) rootUser[0].psd[tempi]);
//        printf("----fornat;%s\n",rootUser[0].psd);
    for (i = 1; i < USER_MAX; i++) {
        strcpy(rootUser[i].name, "\0");
        strcpy(rootUser[i].psd, "\0");
    }
    fwrite(&rootUser, sizeof (User), USER_MAX, fp);
    fclose(fp);

    //	//sect259 在线用户统计文件
    //	fp=fopen(SecterPath(filename,SECT_ONLINE),"w");
    //	char online[USER_MAX*22];
    //	//初始时，密码文件里只有root用户
    //	strcpy(online,"\0");
    //	fwrite(online,sizeof(char),USER_MAX*22,fp); 
    //	fclose(fp);
}

//初始内存

void iniMemo() {
    FILE *fp;
    int i;
    char filename[25],ch;
    Zone myZone;
    
    for (i = 0; i < USER_MAX; i++) {
        fp = fopen(memoZonePath(filename,i),"r");
        ch = fgetc(fp);
        fclose(fp);
        if(ch == EOF){
            //fp = fopen(memoZonePath(filename,i),"w");
            MemoNum = i; 
            printf("%d",MemoNum);//-------------------------------------------------------------------------------------------
            //fputc('a',fp);
           // fclose(fp);
            break;
        } 
    }
    
    
    fp = fopen(SecterPath(filename, SECT_BASE), "r");
    fread(&(myZone.baseMemo), sizeof (BaseSect), 1, fp);
    fclose(fp);


    for (i = 0; i < OPEN_MAX; i++)
        myZone.openFileMemo[i].access = FAIL; //  ->access = FAIL;//        openFileMemo[i].access = FAIL;

    myZone.openedSize = 0;
    myZone.openedSum = 0;


    for (i = 0; i < STRMEMO_MAX; i++) {
        strcpy(myZone.strMemo[i], "\0");
    }
    
    fp = fopen(memoZonePath(filename,MemoNum),"w");
    fwrite(&myZone,sizeof(Zone),1,fp);
    fclose(fp);

}


void releaseMemoZone(){
    char filename[25];
    FILE *fp;
    
    remove(memoZonePath(filename,MemoNum));
    fp = fopen(memoZonePath(filename,MemoNum),"w");
    fclose(fp);
}



//int addUser(char*newName,long modTime)
//{
//	int i,flag=0;
//	char psd[20];
//	char filename[25],stream[CONTENT_MAX],newDir[50];
//	FILE *fp;
//	User user[USER_MAX];
//
//	printf("User Name:");
//	cin>>newName;
//	printf("Password:");
//	cin>>psd;
//	
//	fp=fopen(SecterPath(filename,SECT_PSDFILE),"r");
//	fread(&user,sizeof(User),USER_MAX,fp);
//	fclose(fp);
//	
//	for(i=0;i<USER_MAX;i++){
//		if(strcmp(user[i].name,newName)==0){
//			cout<<"The user name exists ALREADY!\n";
//			return FAIL;
//		}
//	}
//
//	for(i=0;i<USER_MAX;i++){
//		if(strcmp(user[i].name,"\0")==0){
//			strcpy(user[i].name,newName);
//			strcpy(user[i].psd,psd);
//                        flag=1;
//			break;
//		}
//	}
//	if(flag==0){
//            cout<<"TOO MANY users in the system, please delete some users before.";
//            return FAIL;
//        }
//        
//	fp=fopen(SecterPath(filename,SECT_PSDFILE),"w");
//	fwrite(&user,sizeof(User),USER_MAX,fp);
//	fclose(fp);
//	
//	//
//	fp=fopen(SecterPath(filename,SECT_USERDIR),"r");
//	fread(stream,sizeof(char),CONTENT_MAX,fp);
//	fclose(fp);
//
//	newDir[0]='\0';
//	buildDir(newDir,newName,"no",'d',modTime);
//	strcat(stream,newDir);
//
//	fp=fopen(SecterPath(filename,SECT_USERDIR),"w");
//	fwrite(stream,sizeof(char),CONTENT_MAX,fp);
//	fclose(fp);
//
//	return SUCCESS;
//}
//
//
//int delUser(char *name)
//{
//	int i,n,flag;
//	char *p,*q,affirm;
//	char filename[25],stream[CONTENT_MAX],line[50];
//	FILE *fp;
//	User user[USER_MAX];
//
//	printf("Please input the user name to be deleted:");
//	cin>>name;
//        if(strcmp(name,"root")==0){
//            cout<<"NO PERMISSION to delete 'root'\n";
//            return FAIL;
//        }
//
//	cout<<"\n**********************************\n";
//	cout<<"     CONFIRM:[Y]Delete [N]Cancel";
//	cout<<"\n**********************************\n";
//	while(1){
//		cin>>affirm;
//		if(affirm=='y' || affirm=='Y')
//			break;
//		else if(affirm=='n'|| affirm=='N')
//			return FAIL;
//		else
//			printf("The value you entered is NOT valid, please input again:");
//	}
//
//	
//	fp=fopen(SecterPath(filename,SECT_PSDFILE),"r");
//	fread(&user,sizeof(User),USER_MAX,fp);
//	fclose(fp);
//	
//	flag=0;
//	for(i=0;i<USER_MAX;i++){
//		if(strcmp(user[i].name,name)==0){
//			flag=1;
//			strcpy(user[i].name,"\0");
//			strcpy(user[i].psd,"\0");
//			break;
//		}
//	}
//	if(flag==0){
//		printf("User name %s does NOT exist!\n",name);
//		return FAIL;
//	}
//	
//	fp=fopen(SecterPath(filename,SECT_PSDFILE),"w");
//	fwrite(&user,sizeof(User),USER_MAX,fp);
//	fclose(fp);
//	
//	//
//	fp=fopen(SecterPath(filename,SECT_USERDIR),"r");
//	fread(stream,sizeof(char),CONTENT_MAX,fp);
//	fclose(fp);
//
//	p=stream+7;
//	n=strlen(name);
//	
//	while(1){
//		for(i=0;;i++){
//			if(*(p+i)=='-')
//				break;
//			else
//				line[i]=*(p+i);
//		}
//		q=p+i+7;
//		line[i]='\0';
//		flag=0;
//		for(i=0;i<n;i++){
//			if(line[i]!=name[i]){
//				flag=1;
//				break;
//			}
//		}
//		if(flag==0){
//			if(line[i]=='\t'){
//				while(*q!='\0'){
//					*p=*q;
//					p++;
//					q++;
//				}
//				*p='\0';
//
//				fp=fopen(SecterPath(filename,SECT_USERDIR),"w");
//				fwrite(stream,sizeof(char),CONTENT_MAX,fp);
//				fclose(fp);
//				return SUCCESS;
//			}
//		}
//		p=q;
//	}
//	return FAIL;
//
//}

void loadHeadIndex(HeadIndex *headIndex, char *terName) {
    FILE *fp;
    char filename[25];
    if (strcmp(terName, "\0"))
        fp = fopen(remoteSecterPath(filename, terName, SECT_HEADINDEX), "r");
    else
        fp = fopen(SecterPath(filename, SECT_HEADINDEX), "r");
    fread(headIndex, sizeof (HeadIndex), INDEX_MAX, fp);
    fclose(fp);
}

void unloadHeadIndex(HeadIndex *headIndex, char *terName) {
    FILE *fp;
    char filename[25];
    if (strcmp(terName, "\0"))
        fp = fopen(remoteSecterPath(filename, terName, SECT_HEADINDEX), "w");
    else
        fp = fopen(SecterPath(filename, SECT_HEADINDEX), "w");
    fwrite(headIndex, sizeof (HeadIndex), INDEX_MAX, fp);
    fclose(fp);
}

void getMemoZone(Zone *zone){
    FILE *fp;
    char filename[25];
    
    fp = fopen(memoZonePath(filename,MemoNum),"r");
    fread(zone,sizeof(Zone),1,fp);
   
    fclose(fp); 
}

void putMemoZone(Zone *zone){
    FILE *fp;
    char filename[25];
    
    fp = fopen(memoZonePath(filename,MemoNum),"w");
    fwrite(zone,sizeof(Zone),1,fp);
    fclose(fp);
}

int loadToMemo(Zone *myZone, short sect, char *terName) {
    int i;
    FILE *fp;
    char filename[25];
     
    for (i = 0; i < STRMEMO_MAX; i++) {
        if (strcmp(myZone->strMemo[i], "\0") == 0) {
            if (strcmp(terName, "\0"))
                fp = fopen(remoteSecterPath(filename, terName, sect), "r");
            else
                fp = fopen(SecterPath(filename, sect), "r");
            fread(&myZone->strMemo[i], sizeof (char), CONTENT_MAX, fp);
            fclose(fp);
            break;
        }
    }
    myZone->openedSize++;

    return i;
}

void unloadMemo(Zone *myZone, short memoNum) {
    strcpy(myZone->strMemo[memoNum], "\0");
    myZone->openedSize--;
}

void writeBack(char *stream, short sect, char *terName) {
    char filename[25];
    FILE *fp;
    if (strcmp(terName, "\0"))
        fp = fopen(remoteSecterPath(filename, terName, sect), "w");
    else
        fp = fopen(SecterPath(filename, sect), "w");
    fwrite(stream, sizeof (char), CONTENT_MAX, fp);
    fclose(fp);
}

void buildDir(char *strDir, char *filename, char* spms, char ctype, long modTime) {
    char stype[4], smod[20];
    stype[0] = '\t';
    stype[1] = ctype;
    stype[2] = '\t';
    stype[3] = '\0';
    strcat(strDir, filename);
    strcat(strDir, "\t");
    strcat(strDir, spms);
    strcat(strDir, stype);
    strcat(strDir, ctime(&modTime));
    strcat(strDir, "-------");
}




